<template>
  <a-upload
    name="file"
    :multiple="true"
    :action="uploadApi"
    :headers="headers"
    :before-upload="beforeUpload"
    @change="handleChange"
  >
    <a-button> <a-icon type="upload" /> {{buttonName === undefined ? '文件上传' : buttonName }} </a-button>
  </a-upload>
</template>

<script>
import { mapActions } from 'vuex'
import storage from 'store'
import { ACCESS_TOKEN } from '@/store/mutation-types'
export default {
  name: 'pFileUpload',
  props: {
    buttonName: String,
    fileSize: Number,
    formatFiltering: Array
  },
  data () {
    return {
      headers: {
        authorization: 'authorization-text',
        'access-token': storage.get(ACCESS_TOKEN)
      },
      uploadApi: ''
    }
  },
  methods: {
    ...mapActions(['GetApi']),
    getApi () {
      const {
        GetApi
      } = this
      GetApi().then(res => {
        this.uploadApi = res
      })
    },
    handleChange (info) {
      console.log(info)
      if (info.file.status !== 'uploading') {
        console.log(info.file, info.fileList)
      }
      if (info.file.status === 'done' && info.file.response.code === '200') {
        this.$message.success(`${info.file.name} 文件上传成功!`)
      } else if (info.file.status === 'error') {
        this.$message.error(`${info.file.name} 文件上传失败!${info.file.response.message}`)
      }
    },
    // 进行上传前的过滤处理
    beforeUpload (file) {
      // 如果调用者没有设定文件大小的限制，那么默认为10mb
      if (this.fileSize === undefined) {
        // todo 这个直接给fileSize赋值 浏览器控制台会报一个警告
        this.fileSize = 1048576 * 10
      }
      if (file.size > this.fileSize) {
        this.$message.error(`上传文件最大支持${this.fileSize}字节`)
        return false
      }
      // 如果没有传入格式过滤数组，则默认允许所有格式的文件上传
      if (this.formatFiltering === undefined) {
        return true
      }
      const format = this.getForMat(file.name)
      const isUpload = this.filter(format)
      if (isUpload === false) {
        this.$message.error(`不支持的格式`)
        return isUpload
      } else {
        return isUpload
      }
    },
    filter (format) {
      for (let i = 0; i < this.formatFiltering.length; i++) {
        if (this.formatFiltering[i].name === format) {
          return this.formatFiltering[i].isUpload
        }
      }
      // 如果格式过滤数组找不到这个格式则不允许上传
      return false
    },
    getForMat (fileName) {
      let format = ''
      let realFormat = ''
      for (let i = fileName.length - 1; i >= 0; i--) {
        if (fileName[i] === '.') {
          break
        }
        if (fileName[i] !== '.') {
          format = format + fileName[i]
        }
      }
      for (let i = format.length - 1; i >= 0; i--) {
        if (format[i] !== '.') {
          realFormat = realFormat + format[i]
        }
      }
      return realFormat
    }
  },
  created () {
    this.getApi()
  }
}
</script>

<style scoped>

</style>
